//
//  ZFPwdView.m
//  CBT
//
//  Created by Mr.Zhang on 2019/3/12.
//  Copyright © 2019 Mr.Zhang. All rights reserved.
//

#import "ZFPwdView.h"

#define kDotCount 6                              // 密码个数
#define kDotSize CGSizeMake (14, 14)             // 密码点的大小
#define K_Field_Height 46                        // 每一个输入框的高度
#define kLineViewColor UIColorFromRGB(0xCCCCCC)  //边框颜色

@interface ZFPwdView()<UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *viewsArray;

@property (nonatomic, strong) UITextField *pwdTextField;

@property (nonatomic, copy) void (^pwdCompletedBlock)(NSString *password);

@end

@implementation ZFPwdView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self == [super initWithFrame:frame]) {
    
        self.backgroundColor = [UIColor whiteColor];
        
        [self initSubViews];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

+ (void)showZFPwdViewWithInputCompletedBlock:(void (^)(NSString *password))completedBlock {
    
    UIView *bgView = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
    bgView.tag = 10086;
    bgView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.6];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    
    ZFPwdView *pwdView = [[ZFPwdView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 178)];
    [[UIApplication sharedApplication].keyWindow addSubview:pwdView];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:pwdView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame    = pwdView.bounds;
    maskLayer.path     = maskPath.CGPath;
    pwdView.layer.mask = maskLayer;
    
    pwdView.pwdCompletedBlock = completedBlock;
}

#pragma mark - KeyBoardNotificationAction

- (void)keyboardWillShow:(NSNotification*)aNotification {
    
    NSDictionary *userInfo = [aNotification userInfo];
    
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect  = [aValue CGRectValue];
    float keyBoardHeight = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.32 animations:^{
        self.frame = CGRectMake(0, SCREEN_HEIGHT - keyBoardHeight - 178, SCREEN_WIDTH, 178);
    }];
}

- (void)keyboardWillHide:(NSNotification*)aNotification {
    
    [UIView animateWithDuration:0.32 animations:^{
        
        self.frame = CGRectMake(0, SCREEN_HEIGHT + 178, SCREEN_WIDTH,178);
        
        ((UIView *)[[UIApplication sharedApplication].keyWindow viewWithTag:10086]).alpha = 0;
        
    }completion:^(BOOL finished) {
        
        [((UIView *)[[UIApplication sharedApplication].keyWindow viewWithTag:10086])removeFromSuperview];
        
        [self removeFromSuperview];
    }];
}

- (void)initSubViews {
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), 48)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = kLocalizedString(@"请输入支付密码", nil);
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.textColor = UIColorFromRGB(0x0E050B);
    [self addSubview:titleLabel];
    
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) - 60, 0, 60, 48)];
    [cancelBtn setTitle:kLocalizedString(@"取消", nil) forState:(UIControlStateNormal)];
    [cancelBtn setTitleColor:UIColorFromRGB(0x666666) forState:(UIControlStateNormal)];
    [cancelBtn addTarget:self action:@selector(cancalAction:) forControlEvents:(UIControlEventTouchUpInside)];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self addSubview:cancelBtn];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 48, CGRectGetWidth(self.bounds), 1)];
    lineView.backgroundColor = kLineViewColor;
    [self addSubview:lineView];
    
    CGFloat width = (self.frame.size.width - 30) / kDotCount;
    
    for (int i = 0; i < kDotCount - 1; i++) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.pwdTextField.frame) + (i + 1) * width, 75, 1, K_Field_Height)];
        lineView.backgroundColor = kLineViewColor;
        [self addSubview:lineView];
    }
    
    for (int i = 0; i < kDotCount; i++) {
        UIView *blackPointView = [[UIView alloc] initWithFrame:CGRectMake(11 + ceil((width - kDotCount) / 2) + ceil(i * width), CGRectGetMinY(self.pwdTextField.frame) + (K_Field_Height - kDotSize.height) / 2, kDotSize.width, kDotSize.height)];
        blackPointView.backgroundColor = [UIColor blackColor];
        blackPointView.layer.cornerRadius = kDotSize.width / 2.0f;
        blackPointView.clipsToBounds = YES;
        blackPointView.hidden = YES;
        [self addSubview:blackPointView];
        
        [self.viewsArray addObject:blackPointView];
    }
    
    [self.pwdTextField becomeFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidChange:(UITextField *)textField {
    
    for (UIView *views in self.viewsArray) {
        views.hidden = YES;
    }
    for (int i = 0; i < textField.text.length; i++) {
        ((UIView *)[self.viewsArray objectAtIndex:i]).hidden = NO;
    }
    if (textField.text.length == kDotCount) {
        if (self.pwdCompletedBlock != nil) {
            self.pwdCompletedBlock(textField.text);
        }
        
        [self hideKeyboard];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (([NSString isContainsEmoji:string] && ![NSString isNineKeyBoard:string]) || (string.isEmoji && ![NSString isNineKeyBoard:string]) || (([NSString hasEmoji:string] && ![NSString isNineKeyBoard:string]))) {
        return NO;
    }
    
    if (![NSString validateNumber:string]) {
        return NO;
    }
    
    if([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    } else if(string.length == 0) {
        return YES;
    } else if(textField.text.length >= kDotCount) {
        return NO;
    } else {
        return YES;
    }
}


#pragma mark - publick method

- (void)clearUpPassword {
    [self hideKeyboard];
    
    self.pwdTextField.text = nil;
    [self textFieldDidChange:self.pwdTextField];
}

- (void)hideKeyboard {
    [self.pwdTextField resignFirstResponder];
}

- (void)cancalAction:(UIButton *)btn {
    [self hideKeyboard];
    [self removeFromSuperview];
}

#pragma mark - Lazy

- (NSMutableArray *)viewsArray {
    if (!_viewsArray) {
        _viewsArray = [NSMutableArray array];
    }
    return _viewsArray;
}

- (UITextField *)pwdTextField {
    
    if (!_pwdTextField) {
        _pwdTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 75, CGRectGetWidth(self.bounds) - 30, K_Field_Height)];
        _pwdTextField.backgroundColor = [UIColor clearColor];
        _pwdTextField.textColor = [UIColor clearColor];
        _pwdTextField.tintColor = [UIColor clearColor];
        _pwdTextField.delegate  = self;
        _pwdTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _pwdTextField.keyboardType = UIKeyboardTypeNumberPad;
        _pwdTextField.layer.borderColor   = kLineViewColor.CGColor;
        _pwdTextField.layer.cornerRadius  = 8;
        _pwdTextField.layer.masksToBounds = YES;
        _pwdTextField.layer.borderWidth   = 1;
        [_pwdTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        [self addSubview:_pwdTextField];
    }
    return _pwdTextField;
}

-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    NSLog(@"%@ dealloc",[self class]);
}

@end
